package presentation.rest;

import org.codehaus.jackson.JsonGenerator;
import presentation.twitter.Comment;
import presentation.twitter.Tweet;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.StreamingOutput;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

public class TweetStreamingOutput implements StreamingOutput {

	private final List<Tweet> entity;

	private TweetStreamingOutput(List<Tweet> entity) {
		this.entity = entity;
	}

	@Override
	public void write(OutputStream output) throws IOException, WebApplicationException {
		JsonGenerator g = ServiceLocator.JSON_FACTOR.createJsonGenerator(output);

		g.writeStartArray();
		for (Tweet tweet : entity) {
			g.writeStartObject();

			g.writeNumberField("tweetId", tweet.getTweetId());
			g.writeStringField("username", tweet.getUsername());
			g.writeStringField("message", tweet.getMessage());
			g.writeNumberField("date", tweet.getDate().getTime());


			g.writeArrayFieldStart("comments");
			for (Comment comment : tweet.getComments()) {
				g.writeStartObject();
				g.writeStringField("username", comment.getUsername());
				g.writeStringField("comment", comment.getComment());
				g.writeNumberField("date", comment.getDate().getTime());
				g.writeEndObject();
			}
			g.writeEndArray();

			g.writeEndObject();
		}

		g.writeEndArray();
	}

	public static Builder newBuilder() {
		return new Builder();
	}

	public static class Builder {

		private List<Tweet> entity;

		private Builder() {
		}

		public Builder setEntity(List<Tweet> entity) {
			this.entity = entity;
			return this;
		}

		public TweetStreamingOutput build() {
			return new TweetStreamingOutput(entity);
		}
	}
}
